require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const pool = require('./db');
const authRouter = require('./routes/auth');
const menuRouter = require('./routes/menu');
const rolesRouter = require('./routes/roles');
const usersRouter = require('./routes/users');
const hospitalsRouter = require('./routes/hospitals');
const countiesRouter = require('./routes/counties');
const citiesRouter = require('./routes/cities');
const configsRouter = require('./routes/configs');
const devicesRouter = require('./routes/devices');
const logsRouter = require('./routes/logs');

app.use(cors());
app.use(express.json());

// Public endpoint: allow unauthenticated clients (login page, crawlers) to fetch site name
app.get('/public/site-name', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT config_value FROM atb_config WHERE config_name = ? LIMIT 1', ['网站名称']);
    if (rows && rows[0]) return res.json({ value: rows[0].config_value });
    return res.json({ value: null });
  } catch (err) {
    console.error('Failed to fetch public site name:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

app.use('/api', authRouter);
app.use('/api', menuRouter);
app.use('/api', rolesRouter);
app.use('/api', usersRouter);
app.use('/api', hospitalsRouter);
app.use('/api', countiesRouter);
app.use('/api', citiesRouter);
app.use('/api', configsRouter);
app.use('/api', devicesRouter);
app.use('/api', logsRouter);

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Backend listening on http://localhost:${PORT}`);
});